import Axios from 'axios'
import Store from 'store'
import Moment from 'moment'
import JSON5 from 'json5'
import _ from 'lodash'
import {
  Message
} from 'element-ui'
Axios.defaults.timeout = 15000;
/**
 * api环境
 * @param {string} [env = ''] -  api环境
 * @returns {void}
 */
export function api (env = '') {
  switch (env) {
    case 'example':
      Axios.defaults.baseURL = 'https://result.eolinker.com/CyyJ9NE70492e0cc8ce970d6187f0daf5f2454df24efa50?uri=';
      return;
    case 'mock':
      Axios.defaults.baseURL = 'https://result.eolinker.com/CyyJ9NE70492e0cc8ce970d6187f0daf5f2454df24efa50?uri=';
      return;
    case 'develop':
      // Axios.defaults.baseURL = 'http://192.168.2.116:9501';
      Axios.defaults.baseURL = 'https://result.eolinker.com/CyyJ9NE70492e0cc8ce970d6187f0daf5f2454df24efa50?uri=';
      return;
    case 'product':
      Axios.defaults.baseURL = '';
      return;
    case 'json':
      Axios.defaults.baseURL = '';
      return;
    default:
      if (window.location.host.includes('localhost') || window.location.host.includes('192.168') || window.location.host === 'web.u-bao.cn') {
        api('develop');
      } else {
        Axios.defaults.baseURL = '';
      }
  }
}
// 对请求参数做处理
Axios.interceptors.request.use(
  async config => {
    // config.data 去除没有意义的项并且序列化
    config.data = JSON.stringify(_.isObject(config.data) ? _.omitBy(_.omitBy(config.data, _.isNull), _.isUndefined) : config.data);
    // 重新获取token
    if (Store.get('tokens')) {
      if (
        !config.url.includes('/auth') &&
        Moment(new Date().getTime()).unix() > Store.get('tokens').access_expire &&
        Moment(new Date().getTime()).unix() < Store.get('tokens').refresh_expire
      ) {
        await Axios.create().get(`${Axios.defaults.baseURL}user/token`, { u: Store.get('userId') })
          .then(function (response) {
            Store.set('tokens', response.data);
          })
          .catch(function (error) {
            console.error(error);
          });
      }
    }
    // 设置Authorization
    if (Store.get('tokens')) {
      if (Moment(new Date().getTime()).unix() < Store.get('tokens').access_expire) {
        Axios.defaults.authorization = Store.get('tokens').access_token;
      } else if (Moment(new Date().getTime()).unix() < Store.get('tokens').refresh_expire) {
        Axios.defaults.authorization = Store.get('tokens').refresh_token;
      } else {
        Store.remove('tokens');
      }
    }
    // 没有tokens存储则需要重新登录
    if (
      !window.location.href.includes('/auth') &&
      !Store.get('tokens')
    ) {
      window.location.href = '/index.html'
    }
    config.headers = {
      'Content-Type': 'application/json;charset=UTF-8',
      Authorization: Axios.defaults.authorization
    };
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
// 响应拦截器即异常处理
Axios.interceptors.response.use(response => {
  response.data = typeof response.data === 'string' ? JSON5.parse(response.data) : response.data
  if (response && !response.data.code) {
    return response
  }
  return Promise.reject(response)
}, err => {
  if (err && err.response) {
    const errMes = err.response.data.msg;
    switch (err.response.status) {
      case 400:
        Message.error(errMes || '错误请求');
        break;
      case 401:
        Message.error(errMes || '用户未登录');
        break;
      case 403:
        Message.error(errMes || '拒绝访问');
        break;
      case 404:
        Message.error(errMes || '请求错误,未找到该资源');
        break;
      case 405:
        Message.error(errMes || '请求方法未允许');
        break;
      case 406:
        Message.error(errMes || '请求方法不被接受');
        break;
      case 408:
        Message.error(errMes || '请求超时');
        break;
      case 500:
        Message.error(errMes || '服务器端出错');
        break;
      case 501:
        Message.error(errMes || '网络未实现');
        break;
      case 502:
        Message.error(errMes || '网络错误');
        break;
      case 503:
        Message.error(errMes || '服务不可用');
        break;
      case 504:
        Message.error(errMes || '网络超时');
        break;
      case 505:
        Message.error(errMes || 'http版本不支持该请求');
        break;
      default:
        Message.error(errMes || `连接错误${err.response.status}`);
        break;
    }
    return Promise.reject(err)
  }
  return Promise.reject(err)
});

/**
 * 封装get方法
 * @param {string} url - 接口地址
 * @param {object} params = {} - 接口参数
 * @returns {*} Promise
 */

export function get (url, params = {}) {
  return new Promise((resolve, reject) => {
    Axios.get(url, {
      params: params
    })
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 封装delete方法
 * @param {string} url - 接口地址
 * @param {object} params = {} - 接口参数
 * @returns {*} Promise
 */

export function del (url, params = {}) {
  return new Promise((resolve, reject) => {
    Axios.delete(url, {
      params: params
    })
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 封装post请求
 * @param {string} url - 接口地址
 * @param {object} data = {} - 接口参数
 * @returns {*} Promise
 */

export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    Axios.post(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装patch请求
 * @param {string} url - 接口地址
 * @param {object} data = {} - 接口参数
 * @returns {*} Promise
 */

export function patch (url, data = {}) {
  return new Promise((resolve, reject) => {
    Axios.patch(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装put请求
 * @param {string} url - 接口地址
 * @param {object} data = {} - 接口参数
 * @returns {*} Promise
 */

export function put (url, data = {}) {
  return new Promise((resolve, reject) => {
    Axios.put(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}

export function toggleClass (element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}
